from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
UserModel = get_user_model()
from django.contrib.auth.models import User

# 重写系统中的ModelBackend类，并重写authenticate方法
class MyModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 1,判断用户名或者密码是否为空
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return

        # 2，根据用户名或者手机号查询用户
        try:
            user = User.objects.get(username=username)
        except Exception as e1:
            try:
                user = User.objects.get(mobile=username)
            except Exception as e2:
                user = None

        # 3，校验密码是否正确，用户是否有效
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user
        else:
            return None